//
//  ZHNavController.swift
//  ZHWeibo
//
//  Created by user on 15/12/5.
//  Copyright © 2015年 heima. All rights reserved.
//

import UIKit

class ZHNavController: UINavigationController, UIGestureRecognizerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        /**
          * BUG:如果控制器按住边缘向右滑动,再次PUSH新控制器的话,push失败
        */
        self.interactivePopGestureRecognizer?.delegate = self

        // Do any additional setup after loading the view.
    }
//    override func viewWillAppear(animated: Bool) {
//        super.viewWillAppear(true)
//        self.navigationBar.userInteractionEnabled = true
//    }
    
    
//    //重写push方法,判断如果push出来的是第二个控制器,那么就将控制器的返回按钮,改为首页title,否则返回按钮一律改为返回
    override func pushViewController(viewController: UIViewController, animated: Bool) {
        var title = "返回"
        /**
          * 之所以要判断是为了执行后面的viewController.hidesBottomBarWhenPushed = true在第一个控制器push出来之后,再次push的时候生效
        */
        if childViewControllers.count != 0{
            if childViewControllers.count == 1 {
                title = childViewControllers.first?.title ?? title
            }
            viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_back_withtext", title: title, target: self, action: "back")
            // 隐藏底部 tabbar
            viewController.hidesBottomBarWhenPushed = true
        }
        
        /**
        * 加上这句命令可以解决快速点击leftBtn会push多个控制器的BUG
        */
        navigationBar.userInteractionEnabled = false;
        let time = dispatch_time(DISPATCH_TIME_NOW,  10 * Int64(NSEC_PER_MSEC))
        dispatch_after(time, dispatch_get_main_queue()) { () -> Void in
            //printLog(NSThread.currentThread())
            self.navigationBar.userInteractionEnabled = true;
        }
        
        /**
        * 下面这种方式确实可以取消任务,但是只会在afterDelay时间内之前的任务取消
        */
        super.pushViewController(viewController, animated: animated)
    }
    override func popViewControllerAnimated(animated: Bool) -> UIViewController? {
        self.navigationBar.userInteractionEnabled = false
        super.popViewControllerAnimated(animated)
        return self
    }
    
    //私有的方法,子类是无法继承的----相当于OC中只是内部实现,但是没有声明的方法
    @objc private func back() {
        popViewControllerAnimated(true)
    }
    /**
      * 监听手势代理,如果是跟控制器的话,那么就返回false,使得禁用向右滑动的系统效果
    */
    func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {
        return childViewControllers.count != 1
    }
    
    /**
      * 解决阴影问题
    */
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
